﻿using System;
using BusinessObjects.Entities;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;

namespace Data.NHibernateProvider
{
    public sealed class SessionFactory : IDisposable
    {
        private const string CONNECTION_STRING =
            "data source=localhost;Initial Catalog=Test;Integrated Security=SSPI;";

        private static ISessionFactory _sessionFactory;

        public static ISessionFactory GetSessionFactory
        {
            get { return _sessionFactory ?? (_sessionFactory = BuildSessionFactory()); }
        }

        #region IDisposable Members

        public void Dispose()
        {
            if (_sessionFactory != null)
            {
                _sessionFactory.Dispose();
                _sessionFactory = null;
            }
        }

        #endregion

        private static ISessionFactory BuildSessionFactory()
        {
            return Fluently.Configure().Database(MsSqlConfiguration.MsSql2005.ConnectionString(CONNECTION_STRING)).
                Mappings(m => m.FluentMappings.AddFromAssemblyOf<PersonEntity>()).ExposeConfiguration(
                    c => new SchemaUpdate(c).Execute(false, true)).BuildSessionFactory();
        }
    }
}